package vincent.com.layouttest.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by chenzhengwen on 2015/7/17.
 */
public class CustomViewGroup extends ViewGroup {
    private static final int DEFAULT_COLUMN_INTERVAL = 10;
    private static final int DEFAULT_LINE_INTERVAL = 10;

    private int mColumns = 2;
    private int mColumnInterval;
    private int mLineInterval;


    public CustomViewGroup(Context context) {
        this(context, null);
    }

    public CustomViewGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mColumnInterval = (int)(DEFAULT_COLUMN_INTERVAL * getContext().getResources().getDisplayMetrics().density);
        mLineInterval = (int)(DEFAULT_LINE_INTERVAL * getContext().getResources().getDisplayMetrics().density);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        int currentWidht, currentHeight, currentLeft, currentTop;

        int childAreaLeft = this.getPaddingLeft();
        int childAreaRight = this.getMeasuredWidth() - this.getPaddingRight();
        int childAreaTop = this.getPaddingTop();
        int childAreaBottom = this.getMeasuredHeight() - this.getPaddingBottom();

        currentLeft = childAreaLeft;
        currentTop = childAreaTop;

        int childAreaWidth = childAreaRight - childAreaLeft;
        int childAreaHeight = childAreaBottom - childAreaTop;
        int elementWidth = (int)(childAreaWidth - (mColumns - 1) * mColumnInterval)/mColumns;

        int childCount = this.getChildCount();

        for(int i = 0; i < childCount; i++){
            View child = this.getChildAt(i);

            child.measure(MeasureSpec.makeMeasureSpec(elementWidth, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(childAreaHeight, MeasureSpec.AT_MOST));

            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            child.layout(currentLeft, currentTop, currentLeft + childWidth, currentTop + childHeight);

            if(i != 0 && i%mColumns == (mColumns - 1)){
                currentLeft = childAreaLeft;
                currentTop += mLineInterval + childHeight;
            }else{
                currentLeft += mColumnInterval + childWidth;
            }

        }

    }
}
